﻿/* AgileFx Version 2.0
 * An open-source framework for rapid development of applications and services using Microsoft.net
 * Developed by: AgileHead
 * Website: www.agilefx.org
 * This component is licensed under the terms of the Apache 2.0 License.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Text;
using System.Security.Cryptography;

namespace AgileFx.MVC.Utils
{
    public static class AuthHelper
    {
        public static HttpCookie GetAuthTicketWithRoles(string username, string roles, bool persistCookie, TimeSpan lifespan)
        {
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                1, // Ticket version
                username, // Username associated with ticket
                DateTime.Now, // Date/time issued
                DateTime.Now.Add(lifespan), // Date/time to expire
                persistCookie, // "true" for a persistent user cookie
                roles, // User-data, in this case the roles
                FormsAuthentication.FormsCookiePath);// Path cookie valid for


            // Encrypt the cookie using the machine key for secure transport
            string hash = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(
                FormsAuthentication.FormsCookieName, // Name of auth cookie
                hash); // Hashed ticket


            // Set the cookie's expiration time to the tickets expiration time
            if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;

            return cookie;
        }
    }
}
